<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>
          一线督导核验数据录入
          <!-- <navigation /> -->
        </span>
        <el-button
          size="small"
          style="float: right;"
          type="primary"
          @click="getBack()"
          >返回</el-button
        >
      </div>
      <div class="box">
        <div class="Top">
          <el-form :inline="true" :model="dutyFrom" class="demo-form-inline">
            <el-form-item label="重点工作">
              <el-cascader
                ref="taskRef"
                v-model="dutyFrom.taskId"
                :options="tasksList"
                :props="taskProp"
                :show-all-levels="false"
                size="medium"
              >
              </el-cascader>
            </el-form-item>
            <el-form-item label="发生时间">
              <el-date-picker
                v-model="dutyFrom.occurrenceTime"
                type="month"
                size="medium"
                value-format="yyyy-MM"
                placeholder="选择月"
              >
              </el-date-picker>
            </el-form-item>

            <!-- <el-form-item label="附件上传">
                 <el-button type="primary" size="medium" @click="handFileList()">添加</el-button>
            </el-form-item> -->
          </el-form>
          <el-divider content-position="left">添加责任单位</el-divider>
          <div class="point">
            <div
              v-for="(item, index) in dutyFrom.frontLineSupervisionCompanies"
              :key="index"
            >
              <span class="focusInput">
                <b>责任单位</b>
                <el-input
                  placeholder="请输入内容"
                  style="display: inline-block;width:220px;"
                  v-model="item.departmentName"
                  size="medium"
                >
                </el-input>
              </span>
              <span class="focusInput">
                <b>督导核验内容</b>
                <el-input
                  placeholder="请输入内容"
                  style="display: inline-block;width:220px;"
                  v-model="item.content"
                  size="medium"
                >
                </el-input>
              </span>
              <span class="focusInput" style="width:200px;">
                <b>核验结果</b>
                <el-input
                  placeholder="结果"
                  style="display: inline-block;width:80px;"
                  v-model="item.result"
                  size="medium"
                >
                </el-input>
              </span>
              <span class="focusInput" style="width:200px;">
                <b>附件上传：</b>
                <el-button
                  type="text"
                  size="medium"
                  @click="handFileList(index)"
                  >点击添加</el-button
                >
              </span>
              <i class="el-icon-plus add" @click="addData()"></i>
              <i class="el-icon-close remove" @click="deleteDate(index)"></i>
            </div>
          </div>
        </div>
        <!-- <el-divider content-position="left">富文本框</el-divider>
        <div>
          <Editor ref="editor"></Editor>
        </div> -->
        <div class="submit">
          <el-button type="primary" @click="submitForm()">提交</el-button>
        </div>
      </div>
    </el-card>

    <!-- 附件列表弹框 -->
    <el-dialog
      width="60%"
      title="附件列表配置"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :inline="true"
        label-width="95px"
        :model="dutyAffix"
        :hide-required-asterisk="false"
      >
        <el-form-item label="附件：" prop="file">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-success="successFile"
            :on-remove="handleDealFileRemove"
            :file-list="fileList"
            multiple
            ref="rebateUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import configJson from "../../api/config";
// 引入组件
//import Editor from "@/components/Editor";
import Editor from "@/components/supervisor/Editor";
export default {
  data() {
    return {
      id: "",
      dialogFormVisible: false,
      tasksList: [], //重点工作集合
      deptTypeList: [], //责任单位
      // 表单数据
      dutyFrom: {
        occurrenceTime: "", //月
        taskId: "", //重点工作
        event: "", //富文本
        frontLineSupervisionCompanies: [
          {
            departmentName: "", //责任单位
            result: "合格", //核验结果
            content: "", // 检验内容
            files: [] //图片
          }
        ],
        files: [],
        fileLibType: 13
      },
      // 上传附件模块
      subtasksId: "",
      fileQuarter: 1,
      secondAimsId: "",
      fileList: [],
      fileTableData: [],
      currIndex: 0,
      dutyAffix: {
        id: "",
        taskId: "",
        year: "",
        quarter: "",
        file: [],
        fileType: ""
      },
      fileName: "",
      input: "",
      options: [],
      // 选择附件
      uploadUrl: configJson.API_URL + "fileController/uploadFile",
      tasksList: [],
      taskProp: {
        label: "name",
        value: "id",
        children: "children"
      },
      departmentProp: {
        label: "name",
        value: "id",
        children: "departments"
      }
    };
  },
  mounted() {
    this.gettasksList();
    if (this.$route.query.id) {
      this.getSupervisionId();
    }
    ///this.getdepartmentTypeList();
    // console.log( this.$route.query.id )
  },
  methods: {
    // 文件上传开始--------------------------
    // 上传附件列表
    handFileList(index) {
      this.currIndex = index;

      let _filseArray = this.dutyFrom.frontLineSupervisionCompanies[
        this.currIndex
      ].files;

      if (_filseArray.length != 0) {
        this.dutyAffix.file = [];
        this.fileList = [];
        _filseArray.forEach((item, index) => {
          this.fileList.push({ name: item });
        });
      } else {
        this.fileList = [];
        this.dutyAffix.file = [];
      }
      this.dialogFormVisible = true;
    },
    // 添加附件
    submitForms() {},
    returnFile(val) {
      return `${configJson.API_URL}/fileController/${val}`;
    },
    closeDialog() {
      this.dutyAffix = {
        year: "",
        quarter: "",
        file: [],
        taskId: "",
        id: "",
        fileType: ""
      };
    },
    // 选择附件
    successFile(response, file, fileList) {
      console.log(response);
      if (response.code == 200) {
        this.fileList = fileList;
        console.log(this.fileList);
        let fileUrlStr = this.uploadUrl.split("/");
        let fileRemoveChl = fileUrlStr.slice(0, fileUrlStr.length - 1);
        this.fileUrlEnd = fileRemoveChl.join("/");
        this.fileName = this.fileUrlEnd + "/" + response.data;
        console.log(response.data);
        let _text = response.data;

        console.log(Array.isArray(this.dutyAffix.file));
        console.log(this.dutyAffix.file);
        this.dutyAffix.file.push(_text); //获取上传文件名
        this.dutyFrom.frontLineSupervisionCompanies[this.currIndex].files.push(
          _text
        );
        console.log(this.dutyFrom.frontLineSupervisionCompanies);
        console.log(this.dutyAffix.file);
      }
    },
    handleDealFileRemove(file, fileList) {
      console.log(file, fileList);
      let _text = file.name;
      this.dutyAffix.file.forEach((item, index) => {
        if (item == _text) {
          this.dutyAffix.file.splice(index, 1);
          this.dutyFrom.frontLineSupervisionCompanies[
            this.currIndex
          ].files.splice(index, 1);
        }
      });
    },
    uploadExceed(files, fileList) {
      this.$set(fileList[0], "raw", files[0]);
      this.$set(fileList[0], "name", files[0].name);
      this.$refs["rebateUpload"].clearFiles(); //清除文件
      this.$refs["rebateUpload"].handleStart(files[0]); //选择文件后的赋值方法
      this.fileName = this.fileUrlEnd + "/" + files[0].name;
    },
    // 删除列表附件
    deleteFile(val) {
      this.$axios
        .post(
          `/fileController/deleteFileLib`,
          {
            id: val.id
          },
          2
        )
        .then(res => {
          if (res.code == 200) {
            console.log(res);
            this.$message({
              message: "数据更新成功",
              type: "success"
            });
            this.getfileList();
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // POST /supervision/getSupervisionId
    // 回调获取数据
    getSupervisionId() {
      this.$axios
        .post("/supervision/getSupervisionId", { id: this.$route.query.id }, 2)
        .then(res => {
          if (res.code == 200) {
            this.dutyFrom.occurrenceTime = res.data[0].occurrenceTime;
            this.dutyFrom.taskId = res.data[0].taskId;
            // this.$refs.editor.setContent(res.data[0].event);
            this.dutyFrom.frontLineSupervisionCompanies = [];
            res.data.forEach((item, index) => {
              let _ayy = [];
              if( item.filess.length != 0){
                item.filess.forEach(element => {
                    _ayy.push(element.file)
                });
              }
              this.dutyFrom.frontLineSupervisionCompanies.push({
                departmentName: item.departmentName,
                result: item.result,
                content: item.content,
                files:_ayy
              });
              
  

            });
            // res.data[0].filess.forEach((item, index) => {
            //   this.fileList.push({ name: item.file });
            //   this.dutyAffix.file.push(item.file);
            // });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 添加数据列表
    addData() {
      this.dutyFrom.frontLineSupervisionCompanies.push({
        departmentName: "", //责任单位
        result: "合格", //核验结果
        content: "", // 检验内容
        files: []
      });
    },
    // 删除
    deleteDate(index) {
      if (index == 0) {
        this.$message.error(`无法删除`);
      } else {
        this.dutyFrom.frontLineSupervisionCompanies.splice(index, 1);
      }
    },
    // 重点任务列表
    gettasksList() {
      this.$axios
        .post("task/getList")
        .then(res => {
          if (res.code == 200) {
            res.data.map(item => {
              if (item.children.length == 0) {
                item.children = undefined;
              }
              this.tasksList = res.data;
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    check_num: function() {
      this.dutyFrom.nsScore = this.dutyFrom.nsScore.replace(/[^\d]/g, "");
    },
    // 部门列表
    getdepartmentList(val) {
      this.$axios
        .post("dept/getAllDepartmentTypeId", { id: val }, 2)
        .then(res => {
          if (res.code == 200) {
            this.departmentList = res.data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    getBack() {
      this.$router.go(-1);
    },
    // 上传
    submitForm() {
      // 获取文本框内容
      // this.dutyFrom.event = this.$refs.editor.getUptext();
      // if (this.dutyFrom.event == "") {
      //   this.$message({
      //     message: "富文本框必须填写",
      //     type: "warning"
      //   });
      //   return;
      // }

      this.dutyFrom.files = this.dutyAffix.file;
      let _dutyFrom = JSON.parse(JSON.stringify(this.dutyFrom));
      if (!Array.isArray(_dutyFrom.taskId)) {
        _dutyFrom.taskId = [_dutyFrom.taskId];
      }
      _dutyFrom.taskId = _dutyFrom.taskId[_dutyFrom.taskId.length - 1];
      if (this.$route.query.id) {
        _dutyFrom.id = this.$route.query.id;
      }
      this.$axios
        .post("/supervision/add", _dutyFrom)
        .then(res => {
          if (res.code == 200) {
            this.$message({
              message: "数据添加成功",
              type: "success"
            });
            this.getBack();
            // this.departmentList = res.data;
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  components: { Editor }
};
</script>

<style scoped>
.userIntSize {
  width: 80% !important;
}
.saveBtn {
  width: 55%;
  margin-left: 12%;
}
.selectList {
  display: flex;
}
.boxCount {
  width: 84%;
}
.box {
  width: 100%;
  height: 700px;
}
.point {
  width: 100%;
  height: 150px;
  overflow-y: auto;
  /* background: red; */
}
.focusInput {
  display: inline-block;
  width: 318px;
  height: 40px;
  line-height: 40px;
}
.focusInput > b {
  font-size: 14px;
  width: 120px;
  text-align: right;
  padding-right: 6px;
  font-weight: 500;
  color: #606266;
}
.add {
  font-size: 20px;
  color: #409eff;
  cursor: pointer;
}
.remove {
  font-size: 20px;
  color: #f56c6c;
  margin-left: 10px;
  cursor: pointer;
}
.submit {
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
  margin-top: 6px;
}
</style>
